<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>微信授权登录</title>
  <script src="https://cdn.tailwindcss.com"></script>
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#07C160',
            secondary: '#1677ff',
          },
          fontFamily: {
            sans: ['Inter', 'system-ui', 'sans-serif'],
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .gradient-bg {
        background: linear-gradient(135deg, #07C160 0%, #00B42A 100%);
      }
      .card-shadow {
        box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 8px 10px -6px rgba(0, 0, 0, 0.1);
      }
      .text-shadow {
        text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      }
    }
  </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
  <!-- 顶部导航栏 -->
  <header class="bg-white shadow-sm sticky top-0 z-50">
    <div class="container mx-auto px-4 py-3 flex justify-between items-center">
      <div class="flex items-center space-x-2">
        <i class="fa fa-weixin text-primary text-2xl"></i>
        <span class="font-semibold text-lg text-gray-800">微信登录</span>
      </div>
      <div>
        <button id="helpBtn" class="text-gray-500 hover:text-primary transition-colors duration-200">
          <i class="fa fa-question-circle"></i>
        </button>
      </div>
    </div>
  </header>

  <!-- 主内容区 -->
  <main class="flex-grow container mx-auto px-4 py-8 flex flex-col items-center justify-center">
    <!-- 微信环境检测提示 -->
    <div id="wechatEnvCheck" class="hidden w-full max-w-md mb-6 bg-red-50 border-l-4 border-red-400 p-4 rounded-r shadow-sm">
      <div class="flex">
        <div class="flex-shrink-0">
          <i class="fa fa-exclamation-triangle text-red-500"></i>
        </div>
        <div class="ml-3">
          <p class="text-sm text-red-700">请在微信客户端中打开此页面</p>
        </div>
      </div>
    </div>

    <!-- 登录卡片 -->
    <div id="loginCard" class="w-full max-w-md bg-white rounded-xl shadow-lg overflow-hidden transition-all duration-300 hover:shadow-xl">
      <div class="gradient-bg p-6 text-white text-center">
        <h2 class="text-xl font-bold mb-2 text-shadow">微信授权登录</h2>
        <p class="text-sm opacity-90">获取您的微信信息和手机号</p>
      </div>
      
      <div class="p-6">
        <!-- 授权按钮区域 -->
        <div id="authSection" class="text-center py-8">
          <div class="mb-6">
            <img src="https://picsum.photos/seed/wechat/120/120" alt="微信Logo" class="w-24 h-24 mx-auto object-contain">
          </div>
          
          <p class="text-gray-600 mb-6">
            为了提供更好的服务体验，我们需要获取您的微信信息和绑定的手机号
          </p>
          
          <button id="authorizeBtn" class="w-full py-3 px-4 bg-primary text-white rounded-lg shadow-md hover:bg-primary/90 transition-all duration-200 flex items-center justify-center">
            <i class="fa fa-weixin text-xl mr-2"></i>
            <span class="font-medium">微信授权登录</span>
          </button>
          
          <p class="text-xs text-gray-500 mt-4">
            点击登录即表示您同意我们的 <a href="#" class="text-primary hover:underline">用户协议</a> 和 <a href="#" class="text-primary hover:underline">隐私政策</a>
          </p>
        </div>
        
        <!-- 加载状态 (默认隐藏) -->
        <div id="loadingSection" class="hidden text-center py-8">
          <div class="animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mx-auto mb-4"></div>
          <p class="text-gray-600">正在获取您的信息...</p>
        </div>
        
        <!-- 用户信息展示 (默认隐藏) -->
        <div id="userInfo" class="hidden text-center py-4">
          <div class="mb-4">
            <img id="userAvatar" src="" alt="用户头像" class="w-20 h-20 rounded-full mx-auto object-cover border-4 border-gray-100 shadow-sm">
          </div>
          <h3 id="userName" class="text-lg font-semibold text-gray-800 mb-1"></h3>
          <p id="userId" class="text-gray-600 text-sm mb-2">用户ID: <span class="font-medium"></span></p>
          <p id="userPhone" class="text-gray-600 text-sm mb-4">手机号: <span class="font-medium"></span></p>
          
          <div class="grid grid-cols-2 gap-3 mt-6">
            <button id="logoutBtn" class="px-4 py-2 bg-gray-200 text-gray-700 rounded-lg hover:bg-gray-300 transition-colors">
              <i class="fa fa-sign-out mr-1"></i> 退出登录
            </button>
            <button id="continueBtn" class="px-4 py-2 bg-primary text-white rounded-lg hover:bg-primary/90 transition-colors">
              <i class="fa fa-arrow-right mr-1"></i> 继续访问
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 提示卡片 -->
    <div class="w-full max-w-md mt-6 bg-blue-50 border-l-4 border-blue-400 p-4 rounded-r shadow-sm">
      <div class="flex">
        <div class="flex-shrink-0">
          <i class="fa fa-info-circle text-blue-500"></i>
        </div>
        <div class="ml-3">
          <p class="text-sm text-blue-700">
            <span class="font-medium">温馨提示：</span>请确保您的微信已绑定手机号
          </p>
        </div>
      </div>
    </div>
  </main>

  <!-- 帮助模态框 -->
  <div id="helpModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden transform transition-all">
      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold text-gray-800">使用帮助</h3>
          <button id="closeHelpBtn" class="text-gray-400 hover:text-gray-500">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="space-y-4 text-sm text-gray-600">
          <div>
            <h4 class="font-medium text-gray-800 mb-1">如何使用微信授权登录？</h4>
            <p>请在微信中打开此页面，点击"微信授权登录"按钮，按照提示完成授权即可。</p>
          </div>
          <div>
            <h4 class="font-medium text-gray-800 mb-1">为什么需要获取我的手机号？</h4>
            <p>为了提供更完善的服务体验，我们需要获取您的手机号进行身份验证。</p>
          </div>
          <div>
            <h4 class="font-medium text-gray-800 mb-1">我的信息安全吗？</h4>
            <p>我们采用了严格的加密措施保护您的个人信息，不会向第三方泄露。</p>
          </div>
        </div>
      </div>
      <div class="bg-gray-50 px-6 py-3 flex justify-end">
        <button id="confirmHelpBtn" class="px-4 py-1.5 bg-primary text-white rounded hover:bg-primary/90 transition-colors text-sm">
          我知道了
        </button>
      </div>
    </div>
  </div>

  <!-- 错误提示模态框 -->
  <div id="errorModal" class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 hidden">
    <div class="bg-white rounded-lg shadow-xl w-full max-w-md mx-4 overflow-hidden transform transition-all">
      <div class="p-6">
        <div class="flex justify-between items-center mb-4">
          <h3 class="text-lg font-semibold text-gray-800">操作失败</h3>
          <button id="closeErrorBtn" class="text-gray-400 hover:text-gray-500">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="text-sm text-gray-600">
          <p id="errorMessage">授权过程中出现错误，请稍后再试。</p>
        </div>
      </div>
      <div class="bg-gray-50 px-6 py-3 flex justify-end">
        <button id="retryBtn" class="px-4 py-1.5 bg-primary text-white rounded hover:bg-primary/90 transition-colors text-sm">
          重试
        </button>
      </div>
    </div>
  </div>

  <!-- 页脚 -->
  <footer class="bg-white border-t border-gray-200 py-4">
    <div class="container mx-auto px-4 text-center text-gray-500 text-xs">
      <p>© 2025 微信登录服务 | 隐私政策 | 用户协议</p>
    </div>
  </footer>

  <script>
    // 检测是否在微信浏览器中
    function isWechatBrowser() {
      const ua = navigator.userAgent.toLowerCase();
      return ua.indexOf('micromessenger') !== -1;
    }

    // 检查微信环境
    function checkWechatEnvironment() {
      if (!isWechatBrowser()) {
        document.getElementById('wechatEnvCheck').classList.remove('hidden');
        document.getElementById('authorizeBtn').disabled = true;
        document.getElementById('authorizeBtn').classList.add('opacity-50', 'cursor-not-allowed');
      } else {
        // 检查URL参数中是否有code和state
        const params = new URLSearchParams(window.location.search);
        const code = params.get('code');
        const state = params.get('state');
        
        if (code && state) {
          // 有code和state参数，表示从微信授权页面返回
          handleAuthCallback(code, state);
        }
      }
    }

    // 处理微信授权回调
    function handleAuthCallback(code, state) {
      // 显示加载状态
      showLoading(true);
      
      // 模拟向后端发送code获取用户信息
      // 实际应用中，这里应该将code发送到后端，由后端换取access_token和用户信息
      setTimeout(() => {
        // 模拟获取用户信息成功
        const userInfo = {
          id: 'wx_1234567890',
          name: '微信用户',
          avatar: 'https://picsum.photos/seed/user/100/100',
          phone: '138****1234'
        };
        
        // 更新UI显示用户信息
        updateUserInfo(userInfo);
        
        // 隐藏加载状态
        showLoading(false);
      }, 1500);
    }

    // 显示/隐藏加载状态
    function showLoading(show) {
      if (show) {
        document.getElementById('authSection').classList.add('hidden');
        document.getElementById('loadingSection').classList.remove('hidden');
        document.getElementById('userInfo').classList.add('hidden');
      } else {
        document.getElementById('authSection').classList.add('hidden');
        document.getElementById('loadingSection').classList.add('hidden');
        document.getElementById('userInfo').classList.remove('hidden');
      }
    }

    // 更新用户信息显示
    function updateUserInfo(userInfo) {
      document.getElementById('userAvatar').src = userInfo.avatar;
      document.getElementById('userAvatar').alt = `${userInfo.name}的头像`;
      document.getElementById('userName').textContent = userInfo.name;
      document.getElementById('userId').querySelector('span').textContent = userInfo.id;
      document.getElementById('userPhone').querySelector('span').textContent = userInfo.phone;
    }

    // 发起微信授权
    function initiateWechatAuth() {
      // 这里应该替换为你的微信公众号AppID
      const appId = 'wx1234567890abcdef';
      
      // 授权回调URL，需要在微信公众平台配置
      const redirectUri = encodeURIComponent(window.location.href.split('?')[0]);
      
      // 授权作用域，snsapi_userinfo表示获取用户信息
      const scope = 'snsapi_userinfo';
      
      // 生成随机state参数，防止CSRF攻击
      const state = Math.random().toString(36).substr(2, 10);
      
      // 构建微信授权URL
      const authUrl = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appId}&redirect_uri=${redirectUri}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`;
      
      // 保存state到本地存储，用于后续验证
      localStorage.setItem('wechat_auth_state', state);
      
      // 跳转到微信授权页面
      window.location.href = authUrl;
    }

    // 获取手机号（需用户主动授权）
    function getPhoneNumber() {
      // 显示加载状态
      showLoading(true);
      
      // 实际应用中，这里应该调用微信JSSDK的getPhoneNumber接口
      // wx.ready(function() {
      //   wx.getPhoneNumber({
      //     success: function(res) {
      //       const encryptedData = res.encryptedData;
      //       const iv = res.iv;
      //       // 将encryptedData和iv发送到后端解密获取手机号
      //       // ...
      //     },
      //     fail: function(err) {
      //       console.error('获取手机号失败', err);
      //       showError('获取手机号失败，请重试');
      //     }
      //   });
      // });
      
      // 模拟获取手机号成功
      setTimeout(() => {
        // 更新手机号显示
        document.getElementById('userPhone').querySelector('span').textContent = '138****1234';
        
        // 隐藏加载状态
        showLoading(false);
      }, 1500);
    }

    // 显示错误提示
    function showError(message) {
      document.getElementById('errorMessage').textContent = message;
      document.getElementById('errorModal').classList.remove('hidden');
    }

    // 登出功能
    document.getElementById('logoutBtn').addEventListener('click', () => {
      // 清除本地存储中的用户信息
      localStorage.removeItem('wechat_user_info');
      
      // 重置UI
      document.getElementById('userInfo').classList.add('hidden');
      document.getElementById('authSection').classList.remove('hidden');
    });

    // 继续访问功能
    document.getElementById('continueBtn').addEventListener('click', () => {
      alert('登录成功，即将跳转到主页！');
      // 实际应用中，这里可以进行页面跳转
      // window.location.href = '/home';
    });

    // 微信授权按钮点击事件
    document.getElementById('authorizeBtn').addEventListener('click', () => {
      if (isWechatBrowser()) {
        initiateWechatAuth();
      } else {
        showError('请在微信客户端中打开此页面');
      }
    });

    // 帮助模态框控制
    document.getElementById('helpBtn').addEventListener('click', () => {
      document.getElementById('helpModal').classList.remove('hidden');
    });
    
    document.getElementById('closeHelpBtn').addEventListener('click', () => {
      document.getElementById('helpModal').classList.add('hidden');
    });
    
    document.getElementById('confirmHelpBtn').addEventListener('click', () => {
      document.getElementById('helpModal').classList.add('hidden');
    });

    // 错误模态框控制
    document.getElementById('closeErrorBtn').addEventListener('click', () => {
      document.getElementById('errorModal').classList.add('hidden');
    });
    
    document.getElementById('retryBtn').addEventListener('click', () => {
      document.getElementById('errorModal').classList.add('hidden');
      // 重新尝试获取用户信息
      const params = new URLSearchParams(window.location.search);
      const code = params.get('code');
      const state = params.get('state');
      
      if (code && state) {
        handleAuthCallback(code, state);
      } else {
        initiateWechatAuth();
      }
    });

    // 页面加载完成后检查微信环境
    document.addEventListener('DOMContentLoaded', checkWechatEnvironment);
  </script>
</body>
</html>
    